"use strict"

const express = require("express");
//const { request } = require("http");

// 一个工具类
const app = express();

// 使用中间件来解析 JSON 请求体
app.use(express.json());
 
// 设置全局的 CORS 头部（注意：在生产环境中，不要使用 '*'，而是指定允许的源）
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type");
    next();
});

// 定义路由规则
app.get("/server", (request, response)=>{
    console.log("get!", request.body);
    response.setHeader('Content-Type', 'application/json;charset=UTF-8');
    //response.setHeader("Access-Control-Allow-Origin", "*");
    response.send({rc:"success"});
    //response.sendFile("../user_page.html");
});

app.post("/server", (request, response)=>{
    console.log("post!", request.body, typeof request.body);
    //response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader('Content-Type', 'application/json;charset=UTF-8');
    if (request.body.opcode === 1)
    {
        response.send({rc:"success"});
    }
    else if (request.body.opcode === 3)
    {
        response.send('[{"name":"A"}, {"name": "B"}, {"name": "C"}]');
    }
    else if (request.body.opcode === 4)
    {
        response.send('{"table":[{"type":"A", "amount":1, "price":10},{"type":"B", "amount":2, "price":20}]}');
    }
    else if (request.body.opcode === 6)
    {
        response.send('{"rc":"success"}');
    }
    else if (request.body.opcode === 8)
    {
        response.send('{"rc": "success", "general_income":12, "total_expenditure":13}');
    }
    else
    {

    }
    
})

// 启动
app.listen(8080, ()=>{ console.log("listen port 8080, successful"); });